package cn.com.tbshuda.mysql.mysql.controller;

import cn.com.tbshuda.mysql.mysql.Bean.Result;
import cn.com.tbshuda.mysql.mysql.Bean.ResultUtil;
import cn.com.tbshuda.mysql.mysql.Bean.UserInfo;
import cn.com.tbshuda.mysql.mysql.acpt.NotName;
import cn.com.tbshuda.mysql.mysql.entity.ParamVO;
import cn.com.tbshuda.mysql.mysql.entity.Upload;
import cn.com.tbshuda.mysql.mysql.mapper.UserMapper;
import cn.com.tbshuda.mysql.mysql.packet.PdfUtils;
import com.itextpdf.text.DocumentException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: wsd
 * @date: 2021/8/19 10:09
 */
@Slf4j
@RestController
public class UserController {
    private Boolean ddd = true;

    @Autowired
    private UserMapper userMapper;
//    @NotName
    @PostMapping("/getUser")
    public Result getUser( @RequestBody UserInfo userInfo){
        System.out.println(userInfo);
        return ResultUtil.success("成功了getUser");
    }

//    private final String UPLOAD_PATH = "http://192.168.10.188:8888/path/";
    private final String UPLOAD_PATH = "http://www.tbshuda.com.cn/path/";
//    private final String UPLOAD_URL = "D:\\home\\mysql\\";
    private final String UPLOAD_URL = "/home/pdf/file/";


    @PostMapping("/upload")
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException {
        List name = new ArrayList<>();
        String oldPathName = file.getOriginalFilename();
        String sf = new SimpleDateFormat("yyyy年MM月dd HH-mm:sss").format(new Date());
        String[] suffix = oldPathName.split("[.]");
        String fileName = UUID.randomUUID().toString().replace("-","")+"."+suffix[1];
        String filePath = UPLOAD_URL +fileName;
        String httpPath = UPLOAD_PATH + fileName;
        file.transferTo(new File(filePath));
        name.add(httpPath);
        Upload upload = new Upload();
        upload.setLocalPath(filePath);
        upload.setNewPathName(fileName);
        upload.setOldPathName(oldPathName);
        upload.setSerivePath(UPLOAD_PATH);
        upload.setServiceUrlPro("");
        upload.setCreateTime(new Date());
        upload.setSuffix(suffix[1]);
        upload.setShowFileName(sf);
        userMapper.savePath(upload);
        return ResultUtil.success(upload);
    }
    @GetMapping("getDocList")
    public Result getDocList(@RequestParam("name")String name){
        List<Upload> result = userMapper.getDocList(name);
        return ResultUtil.success(result);
    }
    @GetMapping("/image/pdf")
    public void getDocList(@RequestParam("imageIds")List imageIds, HttpServletRequest request, HttpServletResponse response){
        List<Upload> result = userMapper.getDocListByIds(imageIds);
        String priUrl = UPLOAD_URL;
        MultipartFile[] file = new MultipartFile[result.size()];
        for (int i = 0; i < result.size(); i++) {
            file[i] = fileToMultipartFile(new File(result.get(i).getLocalPath()));
        }
        try {
            PdfUtils.imagesToPdf(file,response,priUrl);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    public MultipartFile fileToMultipartFile(File file) {
        FileItem fileItem = createFileItem(file);
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    private static FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("image", "image/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
    @PostMapping("/img/to/pdf")
    public Result imgToPdf(MultipartFile[] file, HttpServletResponse response) throws IOException {
//        String priUrl = "D:\\home\\mysql\\";
        List name = new ArrayList<>();
        for (MultipartFile file2 : file) {
            String uuid = UUID.randomUUID().toString().replace("-","");
            String filePath = UPLOAD_URL+ uuid+ file2.getOriginalFilename();
            String httpPath = UPLOAD_PATH + uuid + file2.getOriginalFilename();
            file2.transferTo(new File(filePath));
//            name.add(httpPath);
        }
//        try {
//            File pdfFIle = PdfUtils.imagesToPdf(file,response,priUrl);
//            pdfFIle.mkdirs();
//            String pdfPath = "http://192.168.10.188:8888/path/" + pdfFIle.getName();
//            name.add(pdfPath);
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        }
        return ResultUtil.success(name);
    }
    @PostMapping("/imgs/to/pdf")
    public void imgsToPdf(MultipartFile[] file, HttpServletResponse response) throws IOException {
        String priUrl = UPLOAD_URL;
//        String priUrl = "D:\\home\\mysql\\"+fileName+".pdf";
        List name = new ArrayList<>();
//        for (MultipartFile file2 : file) {
//            String uuid = UUID.randomUUID().toString().replace("-","");
//            String filePath = priUrl+ uuid+ file2.getOriginalFilename();
//            String httpPath = "http://192.168.10.188:8888/path/" + uuid + file2.getOriginalFilename();
//            file2.transferTo(new File(filePath));
////            name.add(httpPath);
//        }
        try {
           PdfUtils.imagesToPdf(file,response,priUrl);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
}
